package com.shopnight.controller;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.exceptions.ClientException;
import com.shopnight.dto.WXAuthDto;
import com.shopnight.result.ApiResult;
import com.shopnight.service.UserService;
import com.wf.captcha.ArithmeticCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api")
@Api(tags = {"LoginController"},description = "登录页面所需接口")
@Slf4j
public class LoginController {

    @Autowired
    UserService userService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    public static ArithmeticCaptcha captcha;

    /**
     * 用户登录
     * @param
     * @return
     * @desc <h1>
     * 用Map传参 实在是让人费解 用DTO封装会好很多
     * 原因:如果<你用map形式传参 你整个程式就无法使用Spring数据检查框架 那很遗憾
     * 并且你后面校验map参数会让你很痛苦
     *
     * </h1>
     */

    //获取验证码
//    @PostMapping("/getPhoneVerifyCode")
//    public Object getPhoneVerifyCode(@RequestBody Map<String,Object> phone) throws ClientException {
//        return userService.getPhoneVerifyCode(phone);
//    }
    @PostMapping("/login")
    public Object login( @RequestBody Map<String,Object> verify ) {
        return userService.login(verify);
    }

    @GetMapping("/loginCaptcha")
    @ApiOperation(value = "获取图形验证码",notes = "参数：手机号")
    public void loginVerifyCode(@ApiParam("参数为:phone") HttpServletResponse response,@RequestParam String phone) throws IOException {
       if(phone.length()!=11) {
           response.reset();
           response.setContentType("application/json;charset=utf-8");
           PrintWriter writer = response.getWriter();
           writer.print(  JSON.toJSONString(ApiResult.fail("无效获取")) );
           writer.flush();
           writer.close();
       }else {
           //设置请求头为输出图片的类型
           response.setContentType("image/jpg");
           response.setHeader("Pargam","No-cache");//不需要缓存，确保每次获取新的验证码
           response.setHeader("Cache-Control","no-cache");//缓存控制  no
           response.setDateHeader("Expires",0);//过期

           captcha = new ArithmeticCaptcha(130, 32, 3);
           stringRedisTemplate.opsForValue().set("loginCaptcha:"+ phone , LoginController.captcha.text(),300, TimeUnit.SECONDS);


           try {
               captcha.out(response.getOutputStream());
           }catch (IOException e){
               log.error("验证码生成失败",e.getMessage());
           }

       }

    }


    @GetMapping("/getSessionId")
    public ApiResult<Map<String,String>> getSessionId(@RequestParam("code") String code) {
        return ApiResult.ok(userService.getSessionId(code));
    }

    @PostMapping("/authLogin")
    public ApiResult authLogin(@RequestBody WXAuthDto wxAuthDto){
        String token = userService.authLogin(wxAuthDto);
        return ApiResult.ok("登陆成功!",token);
    }

}
